<template>
  <el-dialog title="区域块管理"
             top="110px"
             :visible.sync="manageBlock"
             :close-on-press-escape="false"
             :close-on-click-modal="false"
             :before-close="closeAllModel">
    <hr class="boundary">
    <div class="body">
      <el-card class="cardGroups">
        <div slot="header" class="clearfix">
          <span>区域块</span>
        </div>
        <div v-for="(item,index) in allBloock" class="campusesList"
             @click="selectCampus(campusType,item.id,item.name,index)">
          {{item.name}}
          <div v-show="showCampusOperate===index" class="operation">
            <i class="el-icon-edit" @click="modifyNewDiv(campusType,index,item.blockName)"></i>
            <i class="el-icon-delete" @click="deleteGroup(campusType,item.id)"></i>
          </div>
        </div>
        <div class="cardFooter"><i class="el-icon-circle-plus" @click="addNewDiv(campusType)"></i></div>
        <div v-show="haveCampuses" class="noData">暂无数据</div>
      </el-card>
      <el-card class="cardGroups">
        <div slot="header" class="clearfix">
          <span>区域</span>
        </div>
        <div v-for="(item,index) in buildingsData" class="buildingsList"
             @click="selectBuilding(buildingType,item.id,item.name,index)">
          {{item.zoneName}}&nbsp;{{item.buildingName}}&nbsp;{{item.name}}
          <div v-show="showBuildingOperate===index" class="operation">
            <i class="el-icon-delete" @click="deleteGroup(buildingType,item.id)"></i>
          </div>
        </div>
        <div class="cardFooter"><i class="el-icon-circle-plus" @click="addClassroom"></i></div>
        <div v-show="haveBuildings" class="noData">暂无数据</div>
      </el-card>

    </div>
    <hr class="boundary">
    <batch-addition :batchAddition="batchAddition" @closeModel="closeModel"></batch-addition>
    <add-room-for-block :show-room="showRoom" @getRoomsList="getRoomsList" :block-id="blockId" @closeModel="closeModel"></add-room-for-block>

    <div slot="footer" class="dialog-footer">
      <el-button type="success" @click="showBatchAddition">批量添加</el-button>
      <el-button @click="closeAllModel">关 闭</el-button>
    </div>
  </el-dialog>

</template>

<script>
  import batchAddition from './groups/batchAddition'
  import addRoomForBlock from "./block/addRoomForBlock";

  export default {
    components: {
      batchAddition,
      addRoomForBlock
    },
    props: {
      manageBlock: Boolean
    },
    data () {
      return {
        showRoom:false,
        showroom:false,
        clickList: true,//分组是否可点
        haveCampuses: true,
        blockId: -1,
        campusType: 0,
        allCampuses: [],
        allBloock: [],
        showCampusOperate: -1,
        haveBuildings: true,
        buildingId: -1,
        buildingType: 1,
        modifyBtn: true,
        buildingsData: [],
        showBuildingOperate: -1,
        haveClassrooms: true,
        classroomId: -1,
        classroomType: 2,
        classroomsData: [],
        showClassroomOperate: -1,
        delGroup: false,
        delId: 0,
        delGroupType: '',
        batchAddition: false,
      }
    },
    methods: {
      // 选择校区
      selectCampus (type, id, name, index) {
        // 判断是否可点
        if (this.clickList === true) {
          this.blockId = id// 保存校区id
          // 清除视图数据
          this.buildingId = -1// 清除楼栋id
          this.buildingsData = []
          this.classroomsData = []
          this.showBuildingOperate = -1// 清除楼栋显示的修改删除按钮
          this.haveClassrooms = true// 选择校区时，教室始终无数据
          // 更改试图样式
          this.selectList(type, name, index)
          // 获取列表
          this.getRoomsList(id)
        } else {
          return false
        }
      },

      // 选择楼栋
      selectBuilding (type, id, name, index) {
        if (this.clickList === true) {
          this.buildingId = id// 保存楼栋id
          this.classroomsData = []
          this.showClassroomOperate = -1
          this.selectList(type, name, index)
          this.getClassroomsList(id)
        } else {
          return false
        }
      },

      // 选择教室
      selectClassroom (type, id, name, index) {
        if (this.clickList === true) {
          this.classroomId = id// 保存教室id
          this.selectList(type, name, index)
        } else {
          return false
        }
      },

      // 选择列表项
      selectList (type, name, index) {
        let campusesList = document.getElementsByClassName('campusesList')
        let buildingsList = document.getElementsByClassName('buildingsList')
        let classroomsList = document.getElementsByClassName('classroomsList')
        if (type === 0) {// 选择校区
          // 修改背景色
          this.changeCSS(campusesList, index)
          // 选中的div显示修改删除按钮
          this.showCampusOperate = index
          // this.showOperate = this.showOperate === index ? -1 : index
        } else if (type === 1) {// 选择楼栋
          this.changeCSS(buildingsList, index)
          this.showBuildingOperate = index
        }
      },

      // 被选中更改样式
      changeCSS (list, index) {
        for (let i = 0; i < list.length; i++) {
          //取空格前的数据--针对楼栋
          let dataName = list[i].innerText.split(' ')[0]
          // 清除按钮导致的回车
          dataName = dataName.replace(/\s/g, '')
          if (i == index) {//被选中
            list[i].style.background = '#BBB'
          } else {
            list[i].style.background = '#FFF'
          }
        }
      },

      // 添加操作
      addNewDiv (type) {
        if (this.modifyBtn === false) {
          return false
        } else {
          // 生成输入div
          let div = document.getElementsByClassName('el-card__body')
          if (div.length >= 5){
            type = 3
          }
          console.log(div)
          let newDiv = document.createElement('div')
          newDiv.setAttribute('class', 'groupList')// 设置class属性
          newDiv.innerHTML = '<input  type="text" style="text-align: center"/>'// 添加input框
          if ((type === 0&&div.length<5)||(type === 3)) {// 添加校区
            console.log("区域块")
            this.addBlock(newDiv)
            this.haveCampuses = false
          } else if (type === 1) {// 添加楼栋
            newDiv.innerHTML = '<input type="text" value="( )" style="text-align: center"/>'
            this.addBuilding(newDiv)
          } else if (type === 2) {// 添加教室
            this.addClassroom(newDiv)
          }
          div[type].appendChild(newDiv)// 插入div
          newDiv.childNodes[0].focus()
        }
      },

      // 增加区域块
      addBlock (newDiv) {
        let self = this
        newDiv.childNodes[0].addEventListener('blur', function () {// input框失焦后的操作
          let newCampus = newDiv.childNodes[0].value// 取值
          // console.log("测试:" + newCampus);
          if (newCampus) {// 存在校区名
            $.ajax({
              type: 'POST',
              url: self.api + 'block',
              headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
              },
              xhrFields: {
                withCredentials: true
              },
              dataType: 'json',
              data: JSON.stringify({
                'name': newCampus
              }),
              success (data) {
                if (data === 1) {// 更新数据并移除输入框
                  newDiv.remove()
                  self.getBlockList()
                  self.$message({
                    message: '区域块添加成功！',
                    type: 'success'
                  })
                  self.modifyBtn = true
                } else if (data.status === 1) {
                  self.clickList = false// 不能切换分组
                  newDiv.childNodes[0].focus()// input框获取焦点
                  self.$message({
                    message: '区域块不能重复！',
                    type: 'warning'
                  })
                  self.modifyBtn = false
                } else {
                  self.modifyBtn = true
                  newDiv.remove()
                  self.getBlockList()
                  self.$message.error('区域块添加失败！')
                }
              }
            })
          } else {// 无校区名
            self.clickList = true
            newDiv.remove()
          }
        })
      },

      // 增加教室
      addClassroom (newDiv) {
        if (this.blockId !== -1) {
          this.showRoom = true
        }
      },

      // 修改操作
      modifyNewDiv (type, index, name, floor) {
        let div = document.getElementsByClassName('el-card__body')
        let newDiv = document.createElement('div')
        newDiv.setAttribute('class', 'groupList')// 设置class属性
        newDiv.innerHTML = '<input type="text" style="text-align: center"/>'// 添加input框
        div[type].insertBefore(newDiv, div[type].childNodes[index + 1])// 插入有input框的div
        div[type].childNodes[index + 2].style.display = 'none'// 隐藏要修改的div
        newDiv.childNodes[0].focus()// input框获取焦点
        newDiv.childNodes[0].value = name// 确保焦点在文字后方
        if (type === 0) {// 添加校区
          this.modifyCampus(div[type], newDiv, index)
        } else if (type === 1) {// 添加楼栋
          newDiv.childNodes[0].value = name + '(' + floor + ')'
          this.modifyBuilding(div[type], newDiv, index)
        } else if (type === 2) {// 添加教室
          this.modifyClassroom(div[type], newDiv, index)
        }
      },

      // 修改校区
      modifyCampus (div, newDiv, index) {
        console.log("test1:"+this.blockId)
        let self = this
        newDiv.childNodes[0].addEventListener('blur', function () {// input框失焦后的操作
          let newCampus = newDiv.childNodes[0].value// 取值
          console.log("test2:"+newDiv.childNodes[0].key)
          if (newCampus) {// 校区名存在数据
            $.ajax({
              type: 'PUT',
              url: self.api + 'block',
              headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
              },
              xhrFields: {
                withCredentials: true
              },
              dataType: 'json',
              data: JSON.stringify({
                'id': self.blockId,
                'name': newCampus
              }),
              success (data) {
                if (data === 1) {
                  self.getBlockList()
                  newDiv.remove()
                  // 显示修改后的div
                  div.childNodes[index + 1].style.display = 'block'
                  div.childNodes[index + 1].style.background = '#BBB'
                  self.$message({
                    message: '区域块名修改成功！',
                    type: 'success'
                  })
                  self.modifyBtn = true
                } else if (data.status === 1) {
                  self.clickList = false// 不能切换分组
                  newDiv.childNodes[0].focus()// input框获取焦点
                  self.$message({
                    message: '区域块名不能重复！',
                    type: 'warning'
                  })
                  self.modifyBtn = false
                } else {
                  self.getBlockList()
                  self.modifyBtn = true
                  newDiv.remove()
                  // 显示修改后的div
                  div.childNodes[index + 1].style.display = 'block'
                  div.childNodes[index + 1].style.background = '#BBB'
                  self.$message.error('区域块名修改失败！')
                }
              }
            })
          } else {// 校区名无数据
            self.$message.error('区域块名不能为空')
            self.clickList = false
            self.modifyBtn = false
            newDiv.childNodes[0].focus()// input框获取焦点
          }
        })
      },

      // 修改教室
      modifyClassroom (div, newDiv, index) {
        let self = this
        newDiv.childNodes[0].addEventListener('blur', function () {// input框失焦后的操作
          let newClassroom = newDiv.childNodes[0].value// 取值
          let roomFloor = parseInt(newClassroom.replace(/[^0-9]/ig, '').substr(0, 1))// 取楼层
          if (newClassroom) {// 教室名存在数据
            $.ajax({
              type: 'PUT',
              url: self.api + 'rooms',
              headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
              },
              xhrFields: {
                withCredentials: true
              },
              dataType: 'json',
              data: JSON.stringify({
                'id': self.classroomId,
                'name': newClassroom,
                'floors': roomFloor,
                'buildingId': self.buildingId
              }),
              success (data) {
                if (data === 1) {
                  self.getClassroomsList(self.buildingId)
                  newDiv.remove()// 移除div
                  div.childNodes[index + 1].style.display = 'block'
                  div.childNodes[index + 1].style.background = '#BBB'
                  self.$message({
                    message: '教室修改成功！',
                    type: 'success'
                  })
                  self.modifyBtn = true
                } else if (data.status === 1) {
                  self.clickList = false// 不能切换分组
                  newDiv.childNodes[0].focus()// input框获取焦点
                  self.$message({
                    message: '教室名不能重复！',
                    type: 'warning'
                  })
                  self.modifyBtn = false
                } else {
                  self.getClassroomsList(self.buildingId)
                  self.modifyBtn = true
                  newDiv.remove()// 移除div
                  div.childNodes[index + 1].style.display = 'block'
                  div.childNodes[index + 1].style.background = '#BBB'
                  self.$message.error('教室修改失败！')
                }
              }
            })
          } else {// 教室名无数据
            self.$message.error('教室名不能为空')
            self.clickList = false
            self.modifyBtn = false
            newDiv.childNodes[0].focus()
          }
        })
      },

      // 删除操作
      deleteGroup (type, id) {
        let self = this
        if (type === 0) {
          if (confirm("你确定删除该区域块吗？")) {
            $.ajax({
              type: 'DELETE',
              url: this.api + 'block',
              headers: {
                'X-Requested-With': 'XMLHttpRequest'
              },
              xhrFields: {
                withCredentials: true
              },
              data: {'id': id},
              success (data) {
                // let jsonData = JSON.parse(data)
                // if (jsonData.status === 1) {// 删除失败，存在分组
                //   self.$message.error('请将该校区下所有分组删除后再进行该操作！')
                // } else {// 删除成功
                //
                if(data == 1){
                  self.$message({
                    message: '删除区域块成功',
                    type: 'success'
                  })
                  self.getBlockList()
                  self.clearCSS(0)
                  self.getRoomsList(self.blockId)
                }

                //}
              }
            })

          }
        } else if (type === 1) {
          if (confirm("你确定从当前区域块移除该区域吗？")){
            $.ajax({
              type: 'POST',
              url: this.api + 'block/delRoomForBlock',
              headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
              },
              xhrFields: {
                withCredentials: true
              },
              dataType: 'json',
              data: JSON.stringify({
                'roomId': id
              }),
              success (data) {
                if(data == 1){
                  self.$message({
                    message: '已移除该区域',
                    type: 'success'
                  })
                  self.getRoomsList(self.blockId)
                }
                // let jsonData = JSON.parse(data)
                // if (jsonData.status === 1) {// 删除失败，存在分组
                //   self.$message.error('请将该校区下所有分组删除后再进行该操作！')
                // } else {// 删除成功
                //
                //   self.$message({
                //     message: '删除成功',
                //     type: 'success'
                //   })
                //}
              }
            })

          }
        }

      },

      // 清除样式
      clearCSS (type) {
        console.log(type)
        let campusesList = document.getElementsByClassName('campusesList')
        let buildingsList = document.getElementsByClassName('buildingsList')
        let classroomsList = document.getElementsByClassName('classroomsList')
        if (type === 0) {// 选择校区
          this.showCampusOperate = -1
          for (let i = 0; i < campusesList.length; i++) {
            campusesList[i].style.background = '#FFF'
          }
        } else if (type === 1) {// 选择楼栋
          this.showBuildingOperate = -1
          for (let i = 0; i < buildingsList.length; i++) {
            buildingsList[i].style.background = '#FFF'
          }
        } else if (type === 2) {// 选择教室
          this.showClassroomOperate = -1
          for (let i = 0; i < classroomsList.length; i++) {
            classroomsList[i].style.background = '#FFF'
          }
        }
      },

      // 获取区域块列表
      getBlockList () {
        let self = this
        this.clickList = true
        $.ajax({
          type: 'GET',
          async: false,
          url: this.api + 'block/getBlocks',
          headers: {
            'X-Requested-With': 'XMLHttpRequest'
          },
          xhrFields: {
            withCredentials: true
          },
          success (data) {
            if (data.length === 0) {
              self.haveCampuses = true
            } else {
              self.haveCampuses = false
            }
            self.allBloock = data
          },
          error () {
            console.log('获取数据失败')
          }
        })
      },

      // 获取区域列表
      getRoomsList (id) {
        let self = this
        this.clickList = true
        $.ajax({
            type: 'GET',
            url: this.api + 'rooms',
            headers: {
              'X-Requested-With': 'XMLHttpRequest'
            },
            xhrFields: {
              withCredentials: true
            },
            data: {'blockId': id},
            success (data) {
              // self.$emit('updateNav')
              if (data.length === 0) {
                self.haveBuildings = true
              } else {
                self.haveBuildings = false
              }
              self.buildingsData = data
            },
            error () {
              console.log('获取数据失败')
            }
          }
        )
      },

      // 批量添加分组
      showBatchAddition () {
        this.batchAddition = true
      },

      // 关闭子级模态框
      closeModel () {
        this.delGroup = false
        this.showRoom = false
        this.batchAddition = false
      },

      // 关闭模态框
      closeAllModel () {
        this.$emit('closeModel')
      }
    },
    mounted () {
        this.getBlockList()
    }
  }
</script>

<style scoped>
  @import '../../assets/public/model.css';
  @import '../../assets/manageGroups.css';
</style>

<style>
  .groupList {
    padding: 2px 5px 5px 5px;
    border-bottom: 1px solid #BBBBBB;
  }

  input {
    width: 50%;
    padding: 0 0 3px 3px;
    border-top: 0;
    border-left: 0;
    border-right: 0;
    border-bottom: 1px solid #BBB;
    outline: none;
  }
</style>
